Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

  1. [
  2. "((()))",
  3. "(()())",
  4. "(())()",
  5. "()(())",
  6. "()()()"
  7. ]

Solution:

  1. public class Solution {
  2. public List<String> generateParenthesis(int n) {
  3. List<String> res = new ArrayList<String>();
  4. helper(n, 0, 0, "", res);
  5. return res;
  6. }
  7. private void helper(int n, int left, int right, String sol, List<String> res) {
  8. if (right == n) {
  9. res.add(sol);
  10. return;
  11. }
  12. if (left < n) {
  13. helper(n, left + 1, right, sol + "(", res);
  14. }
  15. if (right < left) {
  16. helper(n, left, right + 1, sol + ")", res);
  17. }
  18. }
  19. }